<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product_model extends OC_Model {

	function get_all($params = array()) {
        
        $this->db->select('
            SQL_CALC_FOUND_ROWS a.*,
            b.cp_name,
        ', FALSE);

        $this->db->from('products a');
        $this->db->join('category_product b', 'a.cp_id = b.cp_id', 'left');

        if (isset($params['sort'], $params['order']))
            $this->db->order_by($params['sort'], $params['order']);

        if (isset($params['page'], $params['rows']))
            $this->db->limit($params['rows'], (intval($params['page']-1)*intval($params['rows'])));

        if (isset($params['query']) && $params['query'] != '')
        {
            $query = $params['query'];

            $likes = array_map(
                function($f) use ($query) { return "$f LIKE '%$query%'"; }, 
                array('p_name', 'p_desc')
            );
            
            $this->db->where('('.implode(' OR ', $likes).')');
        }

        return $this->fetch_rows();
    }
    
    function get_by_id($p_id) {
        $this->db->where('p_id', $p_id);
        $qry = $this->db->get('products');
        
        if ($qry->num_rows() > 0) {
            return $qry->row();
        }
        
        return NULL;
    }
    
    function get_images($p_id) {
        $this->db->from('product_images');
        $this->db->where('pi_p_id', $p_id);
        
        return $this->db->get()->result();
        //$this->db->get('Table', limit, offset);
    }
    
    function add($data) {
        return $this->db->insert('products', $data);
    }
    
    function edit($data, $keys) {
        return $this->db->update('products', $data, $keys);
    }
    
    function delete($keys) {
        return $this->db->delete('products', $keys);
    }

    function add_image($data)
    {
        return $this->db->insert('product_images', $data);
    }

    function delete_img($keys)
    {
        $this->db->from('product_images');
        $this->db->where($keys);

        $query  = $this->db->get();
        $images = array();

        if ($query->num_rows() > 0)
        {
            foreach($query->result() as $row)
            {
                $images[] = $row->pi_filename;
            }
        }

        $result = $this->db->delete('product_images', $keys);

        if ($result && count($images) > 0)
        {
            foreach($images as $file)
            {
                @unlink(OC_FRONT_DIR.'ocimages/products/'.$file);
                @unlink(OC_FRONT_DIR.'ocimages/products/thumbnail/'.$file);
            }
        }

        return $result;
    }

}

/* End of file product_model.php */
/* Location: ./applications/module_admin/products/models/product_model.php */